﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Fin
{
	public class BaseHandler
	{
		protected IWorkbook _workbook;
		protected ISheet _sheet;
		protected List<FileInfo> _files;
		protected string _dirPath;
		protected ConfigRoot _configRoot;
		protected Config _typeListItem;

		public BaseHandler(Config typeListItem)
		{
			_typeListItem = typeListItem;
			_workbook = new XSSFWorkbook();
			_sheet = _workbook.CreateSheet("合并");
			_files = new List<FileInfo>();

			_configRoot = ConfigHelper.GetConfig();
		}
		/// <summary>
		///  带文件夹路径的构造函数
		/// </summary>
		/// <param name="path">文件夹路径</param>
		public BaseHandler(string dirPath, Config typeListItem) : this(typeListItem)
		{
			_dirPath = dirPath;
			   var files = Directory.GetFiles(dirPath);
			foreach (var item in files)
			{
				_files.Add(new FileInfo(item));
			}
		}

		public IWorkbook Workbook { get { return _workbook; } }
		public List<FileInfo> Files { get { return _files; } }
		public BaseHandler SetPath(string path) {

			var files = Directory.GetFiles(path);
			foreach (var item in files)
			{
				_files.Add(new FileInfo(item));
			}

			return this;
		}

		/// <summary>
		/// 根据文件夹来合并所有表格
		/// </summary>
		/// <param name="dirPath"></param>
		/// <returns></returns>
		public virtual BaseHandler SumSheet()
		{
			 
			foreach (var file in _files)
			{
				if (_typeListItem.FileExtension.ToLower().Contains(file.Extension.ToLower()))
				{
					using (var fs = File.OpenRead(file.FullName))
					{
						IWorkbook workbook;
						  
						if (file.Extension.ToLower().Contains(".xlsx"))
							workbook = new XSSFWorkbook(fs);
						else if (file.Extension.ToLower().Contains(".csv"))
						{
							workbook =CSVHelper. GetWorkbook(file.FullName);
						}
						else  
						{
							workbook = new HSSFWorkbook(fs);
						}
						ISheet sheet = workbook.GetSheetAt(0);


						for (int i = 0; i < sheet.LastRowNum; i++)
						{

							var newRow = _sheet.CreateRow(_sheet.LastRowNum + 1);
							var row = sheet.GetRow(i+1);
							for (int c = 0; c < row.Cells.Count; c++)
							{
								newRow.CreateCell(c).SetCellValue(NpoiExt.GetValue(row.Cells[c]));


							}
						}
					}
				}
			}

			return this;
		}

		public virtual void SaveAndOpent() {
			//获取当前用户的临时文件夹的路径
			var tempPath = Path.Combine(System.IO.Path.GetTempPath(), "合并_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xlsx");
			FileStream sw = File.Create(tempPath);
			_workbook.Write(sw);
			sw.Close();

			Dispose();
			//打开文件
			System.Diagnostics.Process.Start(tempPath);
			 
		}
		protected void Dispose() {

			_workbook = new XSSFWorkbook();
			_sheet = _workbook.CreateSheet("合并");
			_files = new List<FileInfo>();
		}
	}



}
